/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.GerenciarTREF;

import Biblioteca.Library;
import ClassesUnicas.Profissional;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;

/**
 * FrameMain
 *
 * Versao 1.0
 *
 * Data 13/03/2013
 *
 * @author Igor
 */
public final class FrameMain extends javax.swing.JFrame {

    //Atributos
    Profissional profissionalLogado;
    FrameCRUDProfissional frameCRUPDProfissional;
    FrameLocalizaProfissional frameLocalizaProfissional;

    //Construtores
    /**
     * Creates new form FrameMain
     */
    public FrameMain(Profissional profissionalLogado) {
        initComponents();

        //Centraliza o JFrame
        this.setLocationRelativeTo(null);

        this.setTitle("Gerenciamento" + Library.getVersaoTREF());

        this.frameCRUPDProfissional = null;
        this.frameLocalizaProfissional = null;
        this.profissionalLogado = profissionalLogado;

        preencheStatusBar();

        setExtendedState(JFrame.MAXIMIZED_BOTH);

        //Edita o sair da Aplicacao
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent evt) {
                fecharAplicacao();
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        desktopPanePapelDeParede = new javax.swing.JDesktopPane();
        panelStatusBar = new javax.swing.JPanel();
        labelVersao = new javax.swing.JLabel();
        labelUsuarioLogado = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuGerenciar = new javax.swing.JMenu();
        menuGerenciarProfissionais = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        menuGerenciarSair = new javax.swing.JMenuItem();
        menuPesquisar = new javax.swing.JMenu();
        menuPesquisarProfissionais = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Gerenciamento - TREF ");

        desktopPanePapelDeParede.setToolTipText("");
        desktopPanePapelDeParede.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        desktopPanePapelDeParede.setName(""); // NOI18N

        labelVersao.setText("Versão");

        labelUsuarioLogado.setText("Usuário");

        javax.swing.GroupLayout panelStatusBarLayout = new javax.swing.GroupLayout(panelStatusBar);
        panelStatusBar.setLayout(panelStatusBarLayout);
        panelStatusBarLayout.setHorizontalGroup(
            panelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelStatusBarLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelVersao, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(labelUsuarioLogado, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(317, Short.MAX_VALUE))
        );
        panelStatusBarLayout.setVerticalGroup(
            panelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(labelVersao)
                .addComponent(labelUsuarioLogado))
        );

        menuGerenciar.setText("Gerenciar");

        menuGerenciarProfissionais.setText("Profissionais");
        menuGerenciarProfissionais.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuGerenciarProfissionaisActionPerformed(evt);
            }
        });
        menuGerenciar.add(menuGerenciarProfissionais);
        menuGerenciar.add(jSeparator1);

        menuGerenciarSair.setText("Sair");
        menuGerenciarSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuGerenciarSairActionPerformed(evt);
            }
        });
        menuGerenciar.add(menuGerenciarSair);

        jMenuBar1.add(menuGerenciar);

        menuPesquisar.setText("Pesquisar");

        menuPesquisarProfissionais.setText("Profissionais");
        menuPesquisarProfissionais.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuPesquisarProfissionaisActionPerformed(evt);
            }
        });
        menuPesquisar.add(menuPesquisarProfissionais);

        jMenuBar1.add(menuPesquisar);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPanePapelDeParede)
            .addComponent(panelStatusBar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(desktopPanePapelDeParede, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelStatusBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        getAccessibleContext().setAccessibleDescription("GUI - Formula 1 Simulator");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void menuGerenciarProfissionaisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGerenciarProfissionaisActionPerformed
        //Instancia o Objeto se nao foi instanciado
        if (this.frameCRUPDProfissional == null) {
            this.frameCRUPDProfissional = new FrameCRUDProfissional();
        }
        displayInternalFrame(this.frameCRUPDProfissional);
    }//GEN-LAST:event_menuGerenciarProfissionaisActionPerformed

    private void menuPesquisarProfissionaisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuPesquisarProfissionaisActionPerformed
        // TODO add your handling code here:
        if (this.frameLocalizaProfissional == null) {
            this.frameLocalizaProfissional = new FrameLocalizaProfissional(null, null);
        }
        displayInternalFrame(this.frameLocalizaProfissional);
    }//GEN-LAST:event_menuPesquisarProfissionaisActionPerformed

    private void menuGerenciarSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGerenciarSairActionPerformed
        // TODO add your handling code here:
        fecharAplicacao();
    }//GEN-LAST:event_menuGerenciarSairActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrameMain(null).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JDesktopPane desktopPanePapelDeParede;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JLabel labelUsuarioLogado;
    private javax.swing.JLabel labelVersao;
    private javax.swing.JMenu menuGerenciar;
    private javax.swing.JMenuItem menuGerenciarProfissionais;
    private javax.swing.JMenuItem menuGerenciarSair;
    private javax.swing.JMenu menuPesquisar;
    private javax.swing.JMenuItem menuPesquisarProfissionais;
    private javax.swing.JPanel panelStatusBar;
    // End of variables declaration//GEN-END:variables
    //Outros Metodos
    /**
     * Exibe no DesktopPane os InternalFrames
     *
     * @param internalFrame frame a ser exibido no DesktopPane
     */
    private void displayInternalFrame(JInternalFrame internalFrame) {
        //Adiciona ao desktopPane caso nao tenha sido adicionado ou foi fechado na ultima vez
        if (!checkInternalFramesOpen(this.desktopPanePapelDeParede, internalFrame)) {
            this.desktopPanePapelDeParede.add(internalFrame);
        }

        // Garante que nao é um icone  
        try {
            if (internalFrame.isIcon()) {
                internalFrame.setIcon(false);
            }
        } catch (java.beans.PropertyVetoException e) {
            //tratar erro  
        }

        Library.centralizarFrameOrInternalFrame(this, this.desktopPanePapelDeParede, internalFrame);
        internalFrame.setVisible(true);
    }

    /**
     * Metodo que faz a verificacao se o JInternalFrame foi instaciado no
     * DektopPane
     *
     * @param jDesktopPane jDesktopPane da aplicação
     * @param frame Frame a ser verificado
     * @return valor True se o Frame estiver instanciado
     */
    //construtor recebe o JDesktopPane e o JInternalFrame que deseja verififcar 
    private Boolean checkInternalFramesOpen(JDesktopPane jDesktopPane, JInternalFrame internalFrame) {
        for (int i = 0; i < jDesktopPane.getAllFrames().length; i++) {
            if (jDesktopPane.getAllFrames()[i].equals(internalFrame)) {  //se o internalFrame pesquisado estiver na tela, retornar true  
                return true;
            }
        }
        return false;
    }

    private void preencheStatusBar() {
        labelVersao.setText("Versão: " + Library.getVersaoTREF());
        labelUsuarioLogado.setText("Usuário:");
        if (profissionalLogado != null) {
            labelUsuarioLogado.setText("Usuário: " + profissionalLogado.getIdProfissional() + " - " + profissionalLogado.getNome());
        }
    }

    private void fecharAplicacao() {
        if (JOptionPane.showConfirmDialog(FrameMain.this, "Deseja realmente sair do sistema?", "Atenção", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
            return;
        }
        System.exit(0);
    }
}
